package tech.aistar.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.ibatis.session.SqlSession;
import tech.aistar.mapper.CartMapper;
import tech.aistar.model.entity.Cart;
import tech.aistar.service.ICartService;
import tech.aistar.util.MyBatisUtil;

import java.util.List;

/**
 * 本类用来演示:
 *
 * @author: success
 * @date: 2021/4/23 3:17 下午
 */
public class CartServiceImpl implements ICartService {
    @Override
    public void addCart(Cart cart) {
        SqlSession sqlSession = MyBatisUtil.getSqlSession();
        CartMapper cartMapper = sqlSession.getMapper(CartMapper.class);

        Cart c = cartMapper.find(cart.getProductId(),cart.getUserId());
        if(c == null){
            //直接保存..
            cartMapper.save(cart);
        }else{
            cartMapper.update(cart.getProductId(),cart.getUserId());
        }

        sqlSession.commit();
        MyBatisUtil.closeSqlSession(sqlSession);
    }

    @Override
    public PageInfo<Cart> findAll(Integer userId,Integer pageNow,Integer pageSize) {
        SqlSession sqlSession = MyBatisUtil.getSqlSession();
        CartMapper cartMapper = sqlSession.getMapper(CartMapper.class);
        PageHelper.startPage(pageNow,pageSize);
        List<Cart> cartList =cartMapper.findAll(userId);

        PageInfo<Cart> pageInfo = new PageInfo<>(cartList);
        MyBatisUtil.closeSqlSession(sqlSession);
        return pageInfo;
    }

    @Override
    public int delById(Integer id) {
        SqlSession sqlSession = MyBatisUtil.getSqlSession();
        CartMapper cartMapper = sqlSession.getMapper(CartMapper.class);
        int count = cartMapper.delById(id);
        sqlSession.commit();
        MyBatisUtil.closeSqlSession(sqlSession);
        return count;
    }

    @Override
    public int updatez(Integer id, Integer num) {
        SqlSession sqlSession = MyBatisUtil.getSqlSession();
        CartMapper cartMapper = sqlSession.getMapper(CartMapper.class);
        int count = cartMapper.updatez(id , num);

        sqlSession.commit();
        MyBatisUtil.closeSqlSession(sqlSession);
        return count;
    }
}
